package spider

import (
	"context"
	"encoding/json"
)

type OKEXSpiderResponse struct {
	Code      int             `json:"code"`
	Data      json.RawMessage `json:"data"`
	DetailMsg string          `json:"detailMsg"`
	ErrorCode string          `json:"error_code"`
	ErrorMsg  string          `json:"error_message"`
	Msg       string          `json:"msg"`
}

type OKEXGetServiceListService struct {
	c *Client
}

// Do send request
func (s *OKEXGetServiceListService) Do(ctx context.Context, opts ...RequestOption) (res []*OKEXServiceInfo, err error) {
	r := &request{
		method:   "GET",
		endpoint: "/v2/asset/earn/getActivityList",
	}
	data, err := s.c.callAPI(ctx, r, opts...)
	if err != nil {
		return nil, err
	}
	resp := new(OKEXSpiderResponse)
	err = json.Unmarshal(data, resp)
	if err != nil {
		return nil, err
	}
	res = make([]*OKEXServiceInfo, 0)
	err = json.Unmarshal(resp.Data, &res)
	if err != nil {
		return nil, err
	}
	return res, nil
}

type OKEXServiceInfo struct {
	Unit          string  `json:"unit"`
	ProductStatus bool    `json:"productStatus"`
	Status        int     `json:"status"`
	SumHold       float64 `json:"sumHold"`
	MinHold       float64 `json:"minHold"`
	MaxHold       float64 `json:"maxHold"`
	Period        string  `json:"period"`
	Rate          string  `json:"rate"`
	StartTime     int64   `json:"startTime"`
	EndTime       int64   `json:"endTime"`
}

type OKEXGetEarnListService struct {
	c           *Client
	productType OKEXProductType
}

func (s *OKEXGetEarnListService) ProductType(pType OKEXProductType) *OKEXGetEarnListService {
	s.productType = pType
	return s
}

func (s *OKEXGetEarnListService) Do(ctx context.Context, opts ...RequestOption) (res []*OKEXEarnInfo, err error) {
	r := &request{
		method:   "GET",
		endpoint: "/v2/asset/balance/project-type",
	}
	r.setParam("productsType", s.productType)
	data, err := s.c.callAPI(ctx, r, opts...)
	if err != nil {
		return nil, err
	}
	resp := new(OKEXSpiderResponse)
	err = json.Unmarshal(data, resp)
	if err != nil {
		return nil, err
	}
	stakingList := new(OKEXStakingList)
	err = json.Unmarshal(resp.Data, stakingList)
	if err != nil {
		return nil, err
	}
	res = make([]*OKEXEarnInfo, 0)
	err = json.Unmarshal(stakingList.List, &res)
	if err != nil {
		return nil, err
	}
	return res, nil
}

type OKEXStakingList struct {
	List json.RawMessage `json:"list"`
}

type OKEXEarnInfo struct {
	CurrencyName string            `json:"currencyName"`
	ProjectList  []OKEXServiceInfo `json:"projectList"`
}
